package team.bluepen.supermarket.service;

import org.springframework.stereotype.Service;
import team.bluepen.supermarket.conf.KafkaProperties;
import team.bluepen.supermarket.data.entity.ProductNameStatusAmount;
import team.bluepen.supermarket.kafka.KafkaReceiveCallback;
import team.bluepen.supermarket.kafka.KafkaReceiver;
import team.bluepen.supermarket.kafka.KafkaTopics;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Cheng
 */
@Service
public class ProductNameStatusAmountCountRecvService implements KafkaReceiveCallback<ProductNameStatusAmount> {
    private final KafkaReceiver<ProductNameStatusAmount> receiver;

    private final Map<String, ProductNameStatusAmount> amountHashMap = new HashMap<>();

    public ProductNameStatusAmountCountRecvService(KafkaProperties kafkaProperties) {
        receiver = new KafkaReceiver<>(
                KafkaTopics.STATE_DATA_TOPIC,
                kafkaProperties.getBootstrapServers(),
                "ProductNameStatusAmountRecvServ",
                DataKeys.PRODUCT_NAME_STATE_COUNT,
                ProductNameStatusAmount.deserializer(),
                this);
        receiver.start();
    }

    public Collection<ProductNameStatusAmount> getAmount() {
        return amountHashMap.values();
    }


    @Override
    public void onReceive(ProductNameStatusAmount data) {
        ProductNameStatusAmount old = amountHashMap.get(data.getName());
        if (old != null) {
            amountHashMap.put(data.getName(),
                    ProductNameStatusAmount.add(old, data));
            return;
        }
        amountHashMap.put(data.getName(), data);
    }
}
